<template>
  <scroll-view :scroll-y="true" class="w-11/12 m-auto h-11/12">
    <uni-forms label-position="top">
      <uni-card
        v-for="(item, index) in data.operatorList"
        :key="index"
        title="请填写冰箱记录"
        extra="必填*"
        @tap="handleItemClick(item)"
      >
        <uni-forms-item class="relative">
          <text class="absolute left-0 -top-4">{{ item.formName }}</text>
          <text class="absolute right-0 -top-4">{{
            item.reportId ? '已提交' : '未提交'
          }}</text>
        </uni-forms-item>
      </uni-card>
    </uni-forms>
    <view class="w-11/12 m-auto mb-5">
      <uni-data-select
        v-model="value"
        :localdata="range"
        placeholder="请选择审核人"
        @change="changeSelect"
        :disabled="data.statusName === '已提交' ? true : false"
      ></uni-data-select>
    </view>
    <!-- :disabled="data.statusName === '已提交' ? true : false" -->
    <button
      class="w-2/3 mb-10 rounded-xl"
      style="background-color: #5199ff"
      @click="handleSubmit"
      :disabled="data.statusName === '已提交' ? true : false"
    >
      {{ data.statusName }}
    </button>
  </scroll-view>
</template>

<script lang="ts" setup>
import { getWorks, getWorksTableId } from '@/services/review';
import type { operatorDataList } from '@/services/types/review';
import type {
  SubmitAuditData,
  UserDetailOut,
  SubmitTaskData,
} from '@/services/types/write';
import { queryContactList, submitAudit, submitTask } from '@/services/write';
import { onShow } from '@dcloudio/uni-app';
import { ref } from 'vue';
const data = ref({
  title: '',
  statusName: '',
  operatorList: [] as operatorDataList[],
});
// 工作清单表格id
const workIdList = ref([] as { id: string }[]);
const range: { value: number; text: string; item: UserDetailOut }[] = [];
const value = ref(); //审核人
// 切换审核人
const changeSelect = (e: UniHelper.SelectorPickerOnChange) => {
  value.value = e;
};
// 提交审核人函数
const selectUser = async () => {
  // 用户数据
  const userData = range[value.value].item;
  // 提交审核人
  workIdList.value.map(async (id) => {
    let data: SubmitAuditData = {
      auditDptIds: userData.dptId,
      auditDptNames: userData.dptName,
      auditUserId: userData.id,
      auditUserName: userData.dptName,
      id: id.id,
    };
    const res = await submitAudit(data);
    if (res.msg === 'success') {
      console.log('提交审核人提交成功');
    }
  });
};
// 提交
const handleSubmit = async () => {
  selectUser();
  // 提交任务
  workIdList.value.map(async (item) => {
    const res = await getWorksTableId(item.id);
    if (res.msg === 'success') {
      const data: SubmitTaskData = {
        id: item.id,
        operateItemType: '1',
        operatorDataList: [
          {
            dataOptionInList: [],
            formId: res.data.operatorDataList[0].formId,
            formName: res.data.operatorDataList[0].formName,
            id: res.data.operatorDataList[0].id,
            imgUrl: '',
            operateItemValue: '',
            operateName: res.data.operatorDataList[0].operateName,
            reportId: res.data.operatorDataList[0].reportId!,
          },
          {
            dataOptionInList: [],
            formId: res.data.operatorDataList[1].formId,
            formName: res.data.operatorDataList[1].formName,
            id: res.data.operatorDataList[1].id,
            imgUrl: '',
            operateItemValue: '',
            operateName: res.data.operatorDataList[1].operateName,
            reportId: res.data.operatorDataList[1].reportId!,
          },
        ],
      };
      submitTask(data).then((res) => {
        if (res.msg === 'success') {
          uni.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 1000,
          });
        }
      });
    }
  });
};
onShow(() => {
  workIdList.value = [];
  data.value.operatorList = [];
  getFridgeTask();
  asyncGetContacts();
});
/**
 * 查询是否有冰箱任务以及
 * 冰箱任务是否完成
 */
const getFridgeTask = async () => {
  // 加载中
  uni.showLoading({
    title: '加载中...',
    mask: true,
  });
  // 查询工作任务清单
  const res1 = await getWorks();
  const regex: RegExp = /冰箱记录/;
  if (res1.msg === 'success' && res1.data.length > 0) {
    res1.data.forEach((item) => {
      if (regex.test(item.name!)) {
        data.value.title = item.name!;
        workIdList.value.push({
          id: item.id!,
        });
      }
    });
    if (workIdList.value.length === 0) {
      // 返回上一级页面
      uni.switchTab({
        url: '/pages/myWrite/myWrite',
        complete: (complete) => {
          // 提示没有工作任务
          uni.showToast({
            title: '没有工作任务',
            icon: 'error',
            duration: 1000,
          });
        },
      });
    }
  } else {
    // 返回上一级页面
    uni.switchTab({
      url: '/pages/myWrite/myWrite',
      complete: (complete) => {
        // 提示没有工作任务
        uni.showToast({
          title: '没有工作任务',
          icon: 'error',
          duration: 1000,
        });
      },
    });
  }
  // 根据id查询冰箱任务列表
  if (workIdList.value.length > 0) {
    workIdList.value.map(async (item) => {
      const res = await getWorksTableId(item.id);
      if (res.msg === 'success') {
        if (res.data.workStatus === 1) {
          data.value.statusName = '提交';
        } else {
          data.value.statusName = '已提交';
          // TODU 查找审核人
        }
        const operatorDataList = res.data.operatorDataList;
        if (operatorDataList.length > 0) {
          operatorDataList.forEach((operatorData) => {
            if (operatorData.operateName === '请填写冰箱记录') {
              data.value.operatorList.push(operatorData);
            } else {
              //返回上一级页面
              uni.switchTab({
                url: '/pages/myWrite/myWrite',
                complete: (complete) => {
                  // 提示没有冰箱任务
                  uni.showToast({
                    title: '没有冰箱任务',
                    icon: 'error',
                    duration: 1000,
                  });
                },
              });
              return;
            }
          });
        }
      }
    });
  }

  // 关闭加载中
  uni.hideLoading();
};
/**
 * 通信录地址
 */
const asyncGetContacts = async () => {
  const res = await queryContactList();
  if (res.msg === 'success') {
    let contacts: UserDetailOut[] = [];
    try {
      contacts.push(...res.data[1].userDetailOuts);
    } catch (error) {
      console.log(error);
    } finally {
      contacts.push(...res.data[0].userDetailOuts);
      range.push(
        ...contacts.map((item, index) => {
          return { value: index, text: item.roleName, item: item };
        }),
      );
      value.value = 0;
    }
  }
};
// 携带参数跳转到目标页面
const handleItemClick = (item: operatorDataList) => {
  uni.navigateTo({
    url:
      `/pages/writePages/refrigeratorPage/refrigeratorPage?item=` +
      encodeURIComponent(JSON.stringify(item)),
  });
};
</script>

<style lang="scss" scoped>
::v-deep.uni-card {
  .uni-card__header {
    .uni-card__header-extra {
      .uni-card__header-extra-text {
        color: #ff0000;
      }
    }
  }
}
</style>
